import React from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { getUserInfo } from '@/actions';

class User extends React.Component {
  static propTypes = {
    userActions: PropTypes.object,
    user: PropTypes.object,
    userFetchStatus: PropTypes.string,
  }

  static defaultProps = {
    userActions: {},
    user: {},
    userFetchStatus: 'unfetch',
  }

  constructor() {
    super();
    this.state = {
      user: {},
    };
  }

  getUserInfo = () => {
    const { userFetchStatus } = this.props;
    // 正在请求数据 or 数据请求成功时, 不执行请求数据操作;
    if (userFetchStatus === 'fetching' || userFetchStatus === 'success') {
      return;
    }
    this.props.userActions.getUserInfo('sufangyu');
  }

  render() {
    const { user } = this.props;
    console.log(user);
    return (
      <div className="page page__user">
        <button onClick={this.getUserInfo}>Get User Info</button>
        <div className="user__info">
          <ul>
            <li>{user.login}</li>
            <li>{user.created_at}</li>
          </ul>
        </div>
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  console.log('state =>>>', state);
  const { user, userFetchStatus } = state;
  return {
    user,
    userFetchStatus,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    userActions: bindActionCreators({ getUserInfo }, dispatch),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(User);
